﻿using System;
using System.Linq;
using System.Windows.Forms;
using Common.Tools;
using Domain;
using Domain.Entity;
using mshtml;
using Spider.Service;

namespace Spider.Spiders.Workers
{
    internal partial class QqSprider
    {
        protected override string GetFinalUrl(string sourceContent, PageDataSource dataSource)
        {
            switch (dataSource)
            {
                case PageDataSource.QQVisitor:
                    return sourceContent + Workers.QqSprider.Param;
                    break;
                case PageDataSource.QQSeed:
                    return "http://user.qzone.qq.com/" + sourceContent;
                    break;
                default:
                    return sourceContent;
            }

        }
        /// <summary>
        /// 登录QQ空间
        /// </summary>
        /// <returns></returns>
        private QQAcount DealLoginQQZone()
        {
            var qqAcounts = SpiderService.GetEnabledQqAcountsForZone().OrderBy(x => x.LastLogin);
            var acount = qqAcounts.FirstOrDefault(x => x.MaxVisiteTimes > x.VisitedTimes && x.IsLogin);
            if (acount == null)
            {
                acount = qqAcounts.FirstOrDefault(x => x.MaxVisiteTimes > x.VisitedTimes && !x.IsLogin);
                if (acount == null)
                    throw new Exception("账号已经使用完了");
            }
            //判断是否登录
            else if (Spider.WebBrowser.Document != null && Spider.WebBrowser.Document.Cookie.Contains("skey="))
            {
                var content = Spider.WebBrowser.DocumentText.Replace("QQ登录", "");//排除页尾登录字
                if (!content.Contains("登录"))
                    return acount;
            }
            Spider.WebBrowser.Document.Cookie.Remove(0, (Spider.WebBrowser.Document.Cookie.Count() - 1));
            var loginout = Spider.WebBrowser.Document.GetElementById("tb_logout");
            if (loginout == null)
            {
                Spider.WebBrowser.Navigate("http://qzone.qq.com/");
                SpiderHelper.DelayTime(5);
                loginout = Spider.WebBrowser.Document.GetElementById("tb_logout");
            }
            if (loginout != null)
            {
                IHTMLDocument2 vDocument = (IHTMLDocument2)Spider.WebBrowser.Document.DomDocument;
                vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript"); //弹出确认
                loginout.InvokeMember("click");
                SpiderHelper.DelayTime(5);
            }
            Spider.WebBrowser.Navigate("http://qzone.qq.com/");
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(3);
            //获取网页文档对象，相当于获取网页的全部源码
            HtmlDocument htmlDoc = Spider.WebBrowser.Document;
            try
            {
                var temp = htmlDoc.Window.Frames["login_frame"];
            }
            catch (Exception ex)
            {
                CustomsLog.WriteInfoLog("QQ账号登陆失败，登陆框未找到", ex.ToString());
                return DealLoginQQZone();
            }
            var login_frame = htmlDoc.Window.Frames["login_frame"];
            IHTMLDocument3 loginframe = CorssDomainHelper.GetDocumentFromWindow(login_frame.DomWindow as IHTMLWindow2);
            //切换到设置QQ号码
            var switcher_plogin = loginframe.getElementById("switcher_plogin");
            switcher_plogin.click();
            SpiderHelper.DelayTime(2);
            //设置QQ号码
            var qqNum = loginframe.getElementById("u");
            qqNum.setAttribute("value", acount.QQ);
            //出发提前通知服务器更换账号登陆
            IHTMLDocument2 vDocument0 = loginframe as IHTMLDocument2;
            if (vDocument0 != null)
            {
                vDocument0.parentWindow.execScript(
                    "window.document.getElementById('u').focus();window.document.getElementById('p').focus();");
                SpiderHelper.DelayTime(3);
            }
            //设置QQ密码
            var qqPass = loginframe.getElementById("p");
            qqPass.setAttribute("value", acount.Pass);

            //登录Qzone
            var btnLogin = loginframe.getElementById("login_button");
            btnLogin.click();
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(5);
            RetryLogin(btnLogin, loginframe);
            SpiderService.SetQQZoneLoginState(acount.QQ);
            Workers.QqSprider._hasvisitedDestinationUrl = false;
            _currentAcountVerifyCodeErrorTimes = Workers.QqSprider.AutoWritVerifyCodeErrorTimes > 0 ? Workers.QqSprider.AutoWritVerifyCodeErrorTimes : 1;
            if (Workers.QqSprider.CheckZoneLogsAvaliable)
            {
                CheckZoneLogAvaliable(acount.QQ);
            }
            return acount;
        }
        /// <summary>
        /// 重复试探登录
        /// </summary>
        /// <param name="btnLogin"></param>
        /// <param name="loginframe"></param>
        /// <returns></returns>
        private bool RetryLogin(IHTMLElement btnLogin, IHTMLDocument3 loginframe)
        {
            //判断当前是否已经成功登录系统
            if (Spider.WebBrowser.DocumentText.Contains("留住感动"))
            {
                //设置验证码
                IHTMLElement verifyCode = loginframe.getElementById("verifyimg");
                if (verifyCode != null)
                {
                    var src = verifyCode.getAttribute("src");
                    if (!string.IsNullOrWhiteSpace(src))
                    {
                        AttachVerifyCode(verifyCode, loginframe);
                        while (string.IsNullOrWhiteSpace(Workers.QqSprider.VerifyCode))
                        {
                            Application.DoEvents();
                        }
                        var txtcode = loginframe.getElementById("verifycode");
                        txtcode.setAttribute("value", Workers.QqSprider.VerifyCode);
                        Workers.QqSprider.VerifyCode = null;
                    }

                }
                btnLogin.click();
                while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
                SpiderHelper.DelayTime(5);
                if (!Spider.WebBrowser.Document.Cookie.Contains("skey="))
                {
                    RetryLogin(btnLogin, loginframe);
                }
            }
            return true;
        }
        /// <summary>
        /// 更换验证码
        /// </summary>
        internal void ChangeVerifyCode()
        {
            //获取网页文档对象，相当于获取网页的全部源码
            HtmlDocument htmlDoc = Spider.WebBrowser.Document;
            var login_frame = htmlDoc.Window.Frames["login_frame"];
            IHTMLDocument3 loginframe = CorssDomainHelper.GetDocumentFromWindow(login_frame.DomWindow as IHTMLWindow2);
            var verifyimg = loginframe.getElementById("verifyimg");
            verifyimg.click();
            SpiderHelper.DelayTime(3);
            AttachVerifyCode(verifyimg, loginframe);
        }
        /// <summary>
        /// 拷贝验证码到内存
        /// </summary>
        /// <param name="verifyCode"></param>
        /// <param name="loginframe"></param>
        protected void AttachVerifyCode(IHTMLElement verifyCode, IHTMLDocument3 loginframe)
        {
            IHTMLImgElement img = verifyCode as IHTMLImgElement;
            HTMLDocument doc = loginframe as HTMLDocument;
            HTMLBody body = (HTMLBody)doc.body;
            IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
            rang.add(img as IHTMLControlElement);
            rang.execCommand("Copy", false, null);  //拷贝到内存  
            Workers.QqSprider.VerifyCodeImage = Clipboard.GetImage();
            if (Workers.QqSprider.AutoWritVerifyCode && _currentAcountVerifyCodeErrorTimes > 0)
            {
                var ret = SpiderService.Uu_recognizeByCodeTypeAndBytes(UtilMethod.GetByteImage(Workers.QqSprider.VerifyCodeImage));
                Workers.QqSprider.VerifyCode = ret;
                _currentAcountVerifyCodeErrorTimes--;
            }
        }
        /// <summary>
        /// 申请空间访问
        /// </summary>
        /// <param name="destqq"></param>
        /// <returns></returns>
        private void ApplyZoneVisite(string destqq)
        {
            if (_zoneOpened) return;
            string ret = "";
            string html = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + destqq + "/main");
            if (html == null || !html.Contains("申请访问")) return;
            if (Spider.WebBrowser.Document == null) return;
            HtmlElement aply = null;
            HtmlElement sure = null;
            var anchors = Spider.WebBrowser.Document.GetElementsByTagName("a");
            foreach (HtmlElement anchor in anchors)
            {
                if (anchor.InnerText == "申请访问")
                {
                    aply = anchor;
                    aply.InvokeMember("click");
                    break;
                }
            }
            if (aply == null) ret += "申请访问按钮没找到";
            else
            {
                SpiderHelper.DelayTime(2);
                foreach (HtmlElement anchor in anchors)
                {
                    if (anchor.InnerText == "确定")
                    {
                        sure = anchor;
                        break;
                    }
                }
                var content = Spider.WebBrowser.Document.GetElementById("msg-area");
                if (content == null) ret += "内容框没找到";
                else content.InnerHtml = "你好啊！";
                if (sure == null) ret += "确定按钮没找到";
                else sure.InvokeMember("click");
                SpiderHelper.DelayTime(2);
            }

            if (!string.IsNullOrWhiteSpace(ret))
                CustomsLog.WriteInfoLog("申请空间访问错误", ret);
        }
        /// <summary>
        /// 申请空间加好友,暂不支持时光轴页面，支持权限访问和主页面IE11不兼容
        /// </summary>
        /// <returns></returns>
        private string ApplyZoneAddFriend(string html)
        {
            // if (!html.Contains("申请访问")) return "";
            if (Spider.WebBrowser.Document == null) return "";
            HtmlElement aply = null;
            HtmlElement sure = null;
            var anchors = Spider.WebBrowser.Document.GetElementsByTagName("a");
            foreach (HtmlElement anchor in anchors)
            {
                if (anchor.InnerText != null && anchor.InnerText.Contains("加为好友"))
                {
                    aply = anchor;
                    aply.InvokeMember("click");
                    break;
                }
            }
            if (aply == null) return "加为好友按钮没找到";
            SpiderHelper.DelayTime(2);
            foreach (HtmlElement anchor in anchors)
            {
                if (anchor.InnerText != null && anchor.InnerText.Contains("确定"))
                {
                    sure = anchor;
                    break;
                }
            }
            var content = Spider.WebBrowser.Document.GetElementById("FP-addFriend-verifyinput");
            if (content == null) return "内容框没找到";
            content.InnerHtml = "你好啊！";
            if (sure == null) return "确定按钮没找到";
            sure.InvokeMember("click");
            SpiderHelper.DelayTime(2);
            return "";
        }
        /// <summary>
        /// 留言板页面申请空间加好友,IE11兼容
        /// </summary>
        /// <returns></returns>
        private void ApplyZoneAddFriendByMessageBord(string destqq)
        {
            if (!_zoneOpened) return;
            if (Spider.WebBrowser.Document == null) return;
            string ret = "";
            if (Spider.WebBrowser.Document == null) return;
            var html = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + destqq + "/334");
            if (html == null) return;
            if (!SpiderHelper.ValidateQqZoneOpened(html))
            {
                _zoneOpened = false;
                return;
            }
            try
            {
                var d = Spider.WebBrowser.Document.Window.Frames[0];
                d = Spider.WebBrowser.Document.Window.Frames[1];
            }
            catch (Exception)
            {
                return;//加载失败的空间
            }
            var message_frame = Spider.WebBrowser.Document.Window.Frames[0];
            IHTMLDocument3 messageframe = CorssDomainHelper.GetDocumentFromWindow(message_frame.DomWindow as IHTMLWindow2);
            var anchors = messageframe.getElementsByTagName("a");
            foreach (IHTMLElement anchor in anchors)
            {
                if (anchor.innerText != null && anchor.innerText.Contains("加为好友"))
                {
                    anchor.click();
                    break;
                }
            }
            SpiderHelper.DelayTime(2);
            var friend_frame = Spider.WebBrowser.Document.Window.Frames[1];
            IHTMLDocument3 friendframe = CorssDomainHelper.GetDocumentFromWindow(friend_frame.DomWindow as IHTMLWindow2);
            var sure = friendframe.getElementById("button-friend-verify");
            var content = friendframe.getElementById("textarea-friend-verify");
            if (content != null) ;
            content.innerHTML = "你好啊！";
            if (sure == null) ret += "确定按钮没找到";
            else sure.click();
            SpiderHelper.DelayTime(2);
            if (!string.IsNullOrWhiteSpace(ret))
                CustomsLog.WriteInfoLog("留言板页面申请空间加好友错误", ret);
        }
        /// <summary>
        /// 空间首页，点赞第一个
        /// </summary>
        /// <returns></returns>
        private void ZoneIndexSayGood(string destqq)
        {
            if (!_zoneOpened) return;
            if (Spider.WebBrowser.Document == null) return;
            string ret = "";
            string html = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + destqq + "/main");
            if (html == null) return;
            if (!SpiderHelper.ValidateQqZoneOpened(html))
            {
                _zoneOpened = false;
                return;
            }
            HtmlElement good = null;
            var anchors = Spider.WebBrowser.Document.GetElementsByTagName("a");
            foreach (HtmlElement anchor in anchors)
            {
                if (anchor.InnerText != null && anchor.InnerText.Contains("赞"))
                {
                    good = anchor;
                    good.InvokeMember("click");
                    break;
                }
            }
            if (good == null) ret = "赞按钮没找到";
            else SpiderHelper.DelayTime(2);
            if (!string.IsNullOrWhiteSpace(ret))
                CustomsLog.WriteInfoLog("首页点赞错误", ret);
        }
        /// <summary>
        /// 空间说说页，点赞第一个
        /// </summary>
        /// <returns></returns>
        private void ZoneShuoShuoSayGood(string destqq)
        {
            if (!_zoneOpened) return;
            if (Spider.WebBrowser.Document == null) return;
            string html = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + destqq + "/311");
            if (html == null) return;
            if (!SpiderHelper.ValidateQqZoneOpened(html))
            {
                _zoneOpened = false;
                return;
            }
            IHTMLElement good = null;
            try
            {
                var d = Spider.WebBrowser.Document.Window.Frames[0];
            }
            catch (Exception)
            {
                return;//没有说说的空间
            }

            var shuo_frame = Spider.WebBrowser.Document.Window.Frames[0];
            IHTMLDocument3 shuoframe = CorssDomainHelper.GetDocumentFromWindow(shuo_frame.DomWindow as IHTMLWindow2);
            var anchors = shuoframe.getElementsByTagName("a");
            foreach (IHTMLElement anchor in anchors)
            {
                if (anchor.outerHTML != null && anchor.outerHTML.Contains("_origtemp="))
                {
                    good = anchor;
                    good.click();
                    break;
                }
            }
            SpiderHelper.DelayTime(2);
            return;
        }
        /// <summary>
        /// 检查账号日志是否审核不通过
        /// </summary>
        /// <param name="acount"></param>
        public void CheckZoneLogAvaliable(string acount)
        {
            string ret = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + acount + "/2");
            try
            {
                var d = Spider.WebBrowser.Document.Window.Frames[0];
            }
            catch (Exception)
            {
                return;//加载失败的空间
            }
            var log_frame = Spider.WebBrowser.Document.Window.Frames[0];
            IHTMLDocument3 logframe = CorssDomainHelper.GetDocumentFromWindow(log_frame.DomWindow as IHTMLWindow2);
            var logs = logframe.getElementById("page-container-blog");
            if (logs.innerText.Contains("审核不通过"))
            {
                CustomsLog.WriteInfoLog("日志审核不通过", "账号：" + acount);
            }
        }
        /// <summary>
        /// 空间日志点赞和浏览
        /// </summary>
        /// <param name="destqq"></param>
        public void ZoneLogsSayGood(string destqq)
        {
            if (!_zoneOpened) return;
            if (Spider.WebBrowser.Document == null) return;
            string html = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + destqq + "/2");
            if (html == null) return;
            if (!SpiderHelper.ValidateQqZoneOpened(html))
            {
                _zoneOpened = false;
                return;
            }
            try
            {
                var d = Spider.WebBrowser.Document.Window.Frames[0];
            }
            catch (Exception)
            {
                return;//加载失败的空间
            }
            var log_frame = Spider.WebBrowser.Document.Window.Frames[0];
            IHTMLDocument3 logframe = CorssDomainHelper.GetDocumentFromWindow(log_frame.DomWindow as IHTMLWindow2);
            //获取第一个日志并点击浏览
            var anchors = logframe.getElementsByTagName("a");
            foreach (IHTMLElement anchor in anchors)
            {
                if (anchor.outerHTML != null && anchor.outerHTML.Contains("blogid="))
                {
                    anchor.click();
                    break;
                }
            }
            SpiderHelper.DelayTime(5);
            var spans = logframe.getElementsByTagName("a");
            foreach (IHTMLElement span in spans)
            {
                if (span.innerText != null && span.innerText.Contains("赞") && span.outerHTML.Contains("nline-block"))
                {
                    span.click();
                    break;
                }
            }
            SpiderHelper.DelayTime(2);
        }
        /// <summary>
        /// QQ空间留言板留言
        /// </summary>
        /// <returns></returns>
        private void ZoneBorderLiveMessage(string destqq)
        {
            if (!_zoneOpened) return;
            string ret = "";
            if (Spider.WebBrowser.Document == null) return;
            var html = GetFinalHtmlByWebBrowser("http://user.qzone.qq.com/" + destqq + "/334");
            if (html == null) return;
            if (!SpiderHelper.ValidateQqZoneOpened(html))
            {
                _zoneOpened = false;
                return;
            }
            try
            {
                var d = Spider.WebBrowser.Document.Window.Frames[0];
            }
            catch (Exception)
            {
                return;//加载失败的空间
            }
            string temp = "现在工作怎么样啊？我在做这个，进来看一下吧！老朋友，[url=http://shop115644089.taobao.com/]点击我[/url]" + "  (" + DateTime.Now.ToString() + ")";
            var message_frame = Spider.WebBrowser.Document.Window.Frames[0];
            IHTMLDocument3 messageframe = CorssDomainHelper.GetDocumentFromWindow(message_frame.DomWindow as IHTMLWindow2);
            var sure = messageframe.getElementById("btnPostMsg");
            IHTMLDocument2 vDocument =messageframe as IHTMLDocument2;
            vDocument.parentWindow.execScript(
                "window.frames['veditor1_Iframe'].document.getElementsByTagName('body')[0].innerHTML='"+temp+"'");
            var content = messageframe.getElementById("maskEditor");
            if (content == null) ret += "内容框没找到";
            else
            {
                content.setAttribute("value", temp);
                if (sure == null) ret += "发表按钮没找到";
                else sure.click();
                SpiderHelper.DelayTime(2);
            }
            if (!string.IsNullOrWhiteSpace(ret))
                CustomsLog.WriteInfoLog("QQ空间留言板留言错误", ret);
        }
        /// <summary>
        /// 访问QQ空间时光轴页
        /// </summary>
        /// <returns></returns>
        private void VisiteZoneTimeLine(string destqq, string acount)
        {
            if (!_zoneOpened) return;
            if (Spider.WebBrowser.Document == null) return;
            string url = "http://user.qzone.qq.com/" + destqq + "/main?mode=gfp_timeline";
            var html = GetFinalHtmlByWebBrowser(url);
            if (html == null) return;
            if (!SpiderHelper.ValidateQqZoneOpened(html))
            {
                _zoneOpened = false;
            }
            QQZoneVisitedInfoDto dto = new QQZoneVisitedInfoDto()
            {
                Content = html,
                AccessAcount = acount,
                DestQQNum = destqq
            };
            PageData pageData = new PageData();
            pageData.Data = dto;
            pageData.DataSource = PageDataSource.QQZoneTimeLine;
            pageData.Date = DateTime.Now;
            pageData.PageUrl = url;
            PageRepository.AddPage(pageData);
        }
    }
}
